package com.wxh.concurrent;

/**
 * @ClassName: ThreadHowToStopQuestion
 * @Description: 线程怎样停止问题
 * @Author wxh
 * @Date: 2021/3/18 16:04
 * @Version V1.0.0
 * @Since 1.8
 */
public class ThreadHowToStopQuestion {
    public static void main(String[] args) throws InterruptedException {
        Action action = new Action();
        // 子线程
        Thread t1 = new Thread(action, "t1");
        t1.start();
        // 改变现成的状态
        action.setStopped(true);
        t1.join();

        Thread t2 = new Thread(()->{
            if(Thread.currentThread().isInterrupted()){
                action();
            }
        }, "t2");

        t2.start();
        // 中断线程
        t2.interrupt();
        t2.join();
    }

    private static class Action implements Runnable{
        // 线程安全问题, 确保可见性(happens-before)
        private volatile boolean stopped = false;

        public void setStopped(boolean stopped) {
            this.stopped = stopped;
        }

        @Override
        public void run() {
            if(!stopped){
                // 执行动作
                action();
            }
        }

    }


    private static void action(){
        System.out.printf("线程[%s], 正在执行 \n", Thread.currentThread().getName());
    }
}
